<form class="form-horizontal" method="POST" enctype="multipart/form-data" onsubmit="return isValid()">
    <div class="row-fluid">
        <div class="span6">
            <div class="portlet box green">
                <div class="portlet-title">
                    <div class="caption"><i class="icon-reorder"></i>Бараанууд</div>
                    <div class="tools">
                        <a href="javascript:;" class="collapse"></a>
                    </div>
                </div>
                <div class="portlet-body">
                    <table id="items" class="table table-striped table-bordered table-hover" cellspacing="0" width="100%">
                        <thead>
                            <tr>
                                <th width="70px"></th>
                                <th>Ангилал</th>
                                <th>Бараа</th>
                                <th width="50px">Тоо(ш)</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php $i = 0; ?>
                            <?php $total = 0; ?>
                            <?php foreach ($items as $item): ?>
                                <tr>
                                    <td><a id="delbtn<?php echo ++$i ?>" class="btn mini red" onclick="removeProduct(this);" href="javascript:;"><i class="icon-trash"> Устгах</i></a></td>
                                    <td><?php echo $item['cname'] ?></td>
                                    <td><?php echo $item['pname'] ?></td>
                                    <td>
                                        <input type="hidden" value="<?php echo $item['pid'] ?>" name="items[<?php echo $i ?>][pid]"/>
                                        <input type="hidden" value="<?php echo $item['cname'] ?>" name="items[<?php echo $i ?>][cname]"/>
                                        <input type="hidden" value="<?php echo $item['pname'] ?>" name="items[<?php echo $i ?>][pname]"/>
                                        <input class="pqty" type="number" value="<?php echo $item['qty'] ?>" name="items[<?php echo $i ?>][qty]"/>
                                    </td>
                                    <?php $total += $item['qty']; ?>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                        <tfoot>
                            <tr>
                                <td colspan="3"></td>
                                <td><span id="total_qty"><?php echo $total; ?></span></td>
                            </tr>
                            <tr>
                                <td colspan="3"></td>
                                <td id="td_add_product">
                                    <div>
                                        <label for="category" class="">Ангилал:</label>
                                        <select id="category" class="m-wrap">
                                            <option value="0">[Сонгох]</option>
                                            <?php foreach ($categories as $i => $v): ?>
                                                <option value="<?php echo $i ?>"><?php echo $v ?></option>
                                            <?php endforeach; ?>
                                        </select>

                                        <label for="product" class="">Бараа:</label>
                                        <select id="product" class="m-wrap"></select>

                                        <label for="quantity" class="">Тоо(ш):</label>
                                        <input type="number" id="quantity" class="m-wrap">

                                        <br/>
                                        <br/>
                                        <a class="btn mini green" href="javascript:;" onclick="addProduct()"><i class="icon-plus"></i> Нэмэх</a>
                                    </div>
                                </td>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
        </div>
        <div class="span6">
            <div class="portlet box grey">
                <div class="portlet-title">
                    <div class="caption"><i class="icon-reorder"></i>Салбарууд</div>
                    <div class="tools">
                        <a href="javascript:;" class="collapse"></a>
                    </div>
                </div>
                <div class="portlet-body form">
                    <div class="widget-box">
                        <div class="control-group">
                            <label class="control-label" for="date">Огноо:</label>
                            <div class="controls">
                                <input type="text" name="date" id="date" class="m-wrap input-append date datepicker" data-date-format="yyyy-mm-dd" data-date-viewmode="years" readonly="true" value="<?php echo $date ?>">
                            </div>
                        </div>

                        <div class="control-group">
                            <label class="control-label" for="store_id_from">Салбараас:</label>
                            <div class="controls">
                                <select id="store_id_from" name="store_id_from" class="m-wrap">
                                    <?php foreach ($stores as $i => $v): ?>
                                        <option value="<?php echo $i ?>" <?php echo $i == $storeIdFrom ? 'selected="selected"' : ''; ?>><?php echo $v ?></option>
                                    <?php endforeach; ?>
                                </select>

                                <span>Ажилтан:</span>
                                <select id="user_id_from" name="user_id_from" class="m-wrap"></select>
                            </div>
                        </div>

                        <div class="control-group">
                            <label class="control-label" for="store_id_to">Салбарлуу:</label>
                            <div class="controls">
                                <select id="store_id_to" name="store_id_to" class="m-wrap">
                                    <?php foreach ($stores as $i => $v): ?>
                                        <option value="<?php echo $i ?>" <?php echo $i == $storeIdTo ? 'selected="selected"' : ''; ?>><?php echo $v ?></option>
                                    <?php endforeach; ?>
                                </select>

                                <span>Ажилтан:</span>
                                <select id="user_id_to" name="user_id_to" class="m-wrap"></select>
                            </div>
                        </div>


                        <div class="form-actions">
                            <button type="submit" class="btn green"><i class="icon-plus"></i> Шилжүүлэг хийх</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</form>

<script>
    var itemsTable;
    function addProduct() {
        cat = $('#category').val();
        prod = $('#product').val();
        qty = $('#quantity').val();
        if (!cat || !prod || !qty) {
            alert('Нэмэх ангилал, бараа ба тоог оруулна уу');
            highlight($('#td_add_product'));
        } else {
            i = itemsTable.rows()[0].length + 1;
            while ($('#delbtn' + i).length) {
                i++;
            }
            cname = $('#category option:selected').html();
            pname = $('#product option:selected').html();
            itemsTable.row.add(['<a id="delbtn' + i + '" class="btn mini red" onclick="removeProduct(this);" href="javascript:;"><i class="icon-trash"> Устгах</i></a>',
                cname,
                pname,
                '<input type="hidden" value="' + prod + '" name="items[' + i + '][pid]"/>' +
                        '<input type="hidden" value="' + cname + '" name="items[' + i + '][cname]"/>' +
                        '<input type="hidden" value="' + pname + '" name="items[' + i + '][pname]"/>' +
                        '<input class="pqty" type="number" value="' + qty + '" name="items[' + i + '][qty]"/>'
            ]).draw();
        }
    }

    function removeProduct(ele) {
        if (confirm('Та устгахдаа итгэлтэй байна уу?')) {
            itemsTable.row($(ele).parents('tr')).remove().draw();
        }
    }

    function categoryChanged() {
        sid = $(this).val();
        if (sid > 0) {
            $.ajax({
                url: '<?php echo $urlProduct ?>?category_id=' + sid,
                dataType: 'json',
                success: function(json) {
                    if ($.isEmptyObject(json)) {
                        $('#product').html('<option value="0">[Ангилалд бараа алга]</option>');
                    } else {
                        $('#product').html('');
                        $.each(json, function(i, v) {
                            $('#product').append('<option value="' + i + '">' + v + '</option>');
                        });
                    }
                }
            });
        } else {
            $('#product').html('<option value="0">[Бүгд]</option>');
        }
    }

    function storeFromChanged() {
        sid = $(this).val();
        if (sid > 0) {
            $.ajax({
                url: '<?php echo $urlUser ?>?type=<?php echo UserTable::TYPE_SALES ?>&store_id=' + sid,
                async: false,
                dataType: 'json',
                success: function(json) {
                    if ($.isEmptyObject(json)) {
                        $('#user_id_from').html('<option value="0">[Салбарт зөвлөх алга]</option>');
                    } else {
                        $('#user_id_from').html('');
                        $.each(json, function(i, v) {
                            if (i == <?php echo $userIdFrom ?>) {
                                $('#user_id_from').append('<option value="' + i + '" selected="selected">' + v + '</option>');
                            } else {
                                $('#user_id_from').append('<option value="' + i + '">' + v + '</option>');
                            }
                        });
                    }
                }
            });
        }
    }

    function storeToChanged() {
        sid = $(this).val();
        if (sid > 0) {
            $.ajax({
                url: '<?php echo $urlUser ?>?type=<?php echo UserTable::TYPE_SALES ?>&store_id=' + sid,
                async: false,
                dataType: 'json',
                success: function(json) {
                    if ($.isEmptyObject(json)) {
                        $('#user_id_to').html('<option value="0">[Салбарт зөвлөх алга]</option>');
                    } else {
                        $('#user_id_to').html('');
                        $.each(json, function(i, v) {
                            if (i == <?php echo $userIdTo ?>) {
                                $('#user_id_to').append('<option value="' + i + '" selected="selected">' + v + '</option>');
                            } else {
                                $('#user_id_to').append('<option value="' + i + '">' + v + '</option>');
                            }
                        });
                    }
                }
            });
        }
    }

    function isValid() {
        var valid = true;
        if (confirm('Хадгалах уу?')) {
            if (itemsTable.rows()[0].length < 1) {
                alert('Бараагүй шилжүүлэг байж болохгүй');
                highlight($('#td_add_product'));
                valid = false;
            }
            $.each($('.pqty'), function(i, v) {
                if (isNaN(v.value)) {
                    scrollToElement(v);
                    alert('Тоо биш байна');
                    highlight($(v));
                    valid = false;
                }
                val = parseInt(v.value);
                if (val < 1) {
                    scrollToElement(v);
                    alert('0 ширхэг бараа байж болохгүй');
                    highlight($(v));
                    valid = false;
                }
            });
        } else {
            valid = false;
        }
        return valid;
    }

    $(function() {
        itemsTable = $('#items').DataTable({
            'paging': false,
            "language": {
                "emptyTable": "Хүснэгт хоосон байна.",
                "info": "_START_-с _END_ хүртэл, Нийт: _TOTAL_",
                "infoEmpty": "Нийт: 0",
                "infoFiltered": "(_MAX_ бичлэгээс хайсан)",
                "infoPostFix": "",
                "infoThousands": ",",
                "lengthMenu": "_MENU_ мөр харах",
                "loadingRecords": "Уншиж байна...",
                "processing": "Тооцоолж байна...",
                "search": "Хайлт:",
                "zeroRecords": "Хайлтын үр дүн олдсонгүй",
                "paginate": {
                    "first": "Эхнийх",
                    "last": "Сүүлийнх",
                    "next": "Дараагийнх",
                    "previous": "Өмнөх"
                },
                "aria": {
                    "sortAscending": ": Өсөхөөр эрэмблэх",
                    "sortDescending": ": Буурахаар эрэмблэх"
                }
            }
        });
        $('#category').change(categoryChanged);

        $('#store_id_from').change(storeFromChanged);
        $('#store_id_to').change(storeToChanged);

        $('#store_id_from').change();
        $('#store_id_to').change();

        $(document).on('focus', ':input', function() {
            $(this).attr('autocomplete', 'off');
        });
    });
</script>